package com.xgk.boot.module.core.service.payment;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mzt.logapi.context.LogRecordContext;
import com.mzt.logapi.starter.annotation.LogRecord;
import com.xgk.boot.framework.common.pojo.PageResult;
import com.xgk.boot.module.core.controller.admin.payment.vo.credit.CreditPageReqVO;
import com.xgk.boot.module.core.controller.admin.payment.vo.credit.CreditPageRespVO;
import com.xgk.boot.module.core.controller.admin.payment.vo.credit.CreditSaveReqVO;
import com.xgk.boot.module.core.dal.entity.channel.ServiceProviderDO;
import com.xgk.boot.module.core.dal.entity.customer.CustomerDO;
import com.xgk.boot.module.core.dal.entity.payment.TemporaryCreditDO;
import com.xgk.boot.module.core.dal.iservice.TemporaryCreditService;
import com.xgk.boot.module.core.dal.mapper.payment.TemporaryCreditMapper;
import com.xgk.boot.module.core.service.customer.CustomerBalanceServiceImpl;
import com.xgk.boot.module.core.service.customer.CustomerServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import static com.xgk.boot.module.core.enums.LogRecordConstants.*;


/**
 * 支付管理，
 * 包含 cm-客户、su-供应商、sp-服务商 的收支付信息
 */
@Slf4j
@Service
public class TemoraryCreditServiceImpl extends ServiceImpl<TemporaryCreditMapper, TemporaryCreditDO> implements TemporaryCreditService {

    @Resource
    private TemporaryCreditMapper temporaryCreditMapper;
    @Resource
    private CustomerBalanceServiceImpl customerBalanceServiceImpl;
    @Resource
    private CustomerServiceImpl customerService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    @LogRecord(type = SYSTEM_CREDIT_TYPE, subType = SYSTEM_CREDIT_CREATE_TYPE, bizNo = "{{#tcd.id}}", success = SYSTEM_CREDIT_CREATE_SUCCESS)
    public Long createCredit(CreditSaveReqVO createReqVO) {
        TemporaryCreditDO tcd = new TemporaryCreditDO();
        tcd.setAttachment(createReqVO.getAttachment());
        tcd.setCreditAmount(createReqVO.getCreditAmount());
        tcd.setCustomerId(createReqVO.getCustomerId());
        //默认审批通过，待核销
        tcd.setCreditType(2);
        tcd.setStatus(2);
        tcd.setDueTime(createReqVO.getDueTime());
        tcd.setCreditCode(generateCreditCode());
        temporaryCreditMapper.insert(tcd);
        LogRecordContext.putVariable("tcd", tcd);
        if(tcd.getStatus().equals(2)){
            CustomerDO byId = customerService.getById(tcd.getCustomerId());
            customerBalanceServiceImpl.customerBalanceAddCredit(byId.getCustomerCode(),tcd.getCreditAmount());
        }

        return tcd.getId();
    }

 
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd");
    private static final int MAX_RETRY = 10;

    public String generateCreditCode() {
        int retryCount = 0;

        while(retryCount < MAX_RETRY) {
            String no = tryNumber();

            // 检查数据库中是否已存在该流水号
            Long count = temporaryCreditMapper.selectCount(TemporaryCreditDO::getCreditCode, no);
            if(count == null || count == 0) {
                return no; // 返回唯一的流水号
            }

            retryCount++;
        }

        throw new RuntimeException("无法生成唯一的交易流水号，已达到最大重试次数: " + MAX_RETRY);
    }


    private String tryNumber() {
        String date = DATE_FORMAT.format(new Date());
        String uuidPart = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        return date + uuidPart;
    }
    @Override
    public Page<CreditPageRespVO> getCreditPage(CreditPageReqVO reqVO) {
        // 构建分页参数
        Page<CreditPageRespVO> page = new Page<>(reqVO.getCurrent(), reqVO.getPageSize());

        // 执行分页查询
        return temporaryCreditMapper.selectCreditPage(page, reqVO);
    }
}
